#include "xmltrajectoryreader.h"
#include <vector>

using namespace mlgesture;

XmlTrajectoryReader::XmlTrajectoryReader(std::vector<Trajectory> *trajectories) :
	trajectories_(trajectories) {
}

bool XmlTrajectoryReader::read(QIODevice *device) {
	xml_.setDevice(device);

	if (xml_.readNextStartElement()) {
		if (xml_.name() == "trajectory_set" && xml_.attributes().value("version") == "1.0")
			readTrajectory();
		else
			xml_.raiseError(QObject::tr("The file is not an xml-trajectory file."));
	}

	return !xml_.error();
}

QString XmlTrajectoryReader::errorString() const {
	return QObject::tr("%1\nLine %2, column %3")
			.arg(xml_.errorString())
			.arg(xml_.lineNumber())
			.arg(xml_.columnNumber());
}

void XmlTrajectoryReader::readTrajectory() {
	bool is_trajectory = false;
	Trajectory track;
	QXmlStreamReader::TokenType token;
	while ((token = xml_.readNext()) != QXmlStreamReader::EndDocument) {
		if (token == QXmlStreamReader::StartElement) {
			if (xml_.name() == "trajectory") {
				if (is_trajectory) {
					trajectories_->push_back(track);
				}
				track.type_ = xml_.attributes().value("type").toString().toStdString();
				if (track.type_.empty()) {
					xml_.raiseError(QObject::tr("Undefined trajectory type"));
					return;
				}
				track.data_.clear();
				is_trajectory = true;
			}
			else if (xml_.name() == "direction") {
				bool ok;
				if (!is_trajectory) {
					xml_.raiseError(QObject::tr("Direction outside trajectory element"));
					return;
				}
				int dir =  xml_.readElementText().toInt(&ok);
				if (!ok || dir < 0 || dir > 15) {
					xml_.raiseError(QObject::tr("Wrong direction value"));
					return;
				}
				track.data_.push_back(dir);
			}
			else xml_.skipCurrentElement();
		}
	}
	if (is_trajectory) {
		trajectories_->push_back(track);
	}
}
